<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\api\model\AccountType;
use app\api\model\SetAccount;
use app\api\model\UserModel;
use app\api\validate\CustomerReconciliationValidate;
use app\http\GetUid;
use think\Request;
use app\api\model\SetAccountFlow as Flow;
use app\api\service\CustomerReconciliation as Service;

/**
 * 客户对账
 * Class CustomerReconciliation
 * @package app\api\controller
 */
class CustomerReconciliation extends Common
{
    public function index(Request $request, Flow $model)
    {
        $data = $request->param();
        $data['start_time'] = $data['start_time'] ?? '';
        $data['end_time'] = $data['end_time'] ?? '';
        $data['number'] = $data['number'] ?? '';
        $where = [];
        $where[] = ['customer_id', '=', $data['kid']];
        if ($data['start_time'] && $data['end_time']) {
            $where[] = ['create_time', 'between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['type'])) {
            $where[] = ['account_type_id', '=', $data['type']];
        }
        if (!empty($data['set_account'])) {
            $where[] = ['set_account_id', '=', $data['set_account']];
        }
        if (!empty($data['maker'])) {
            $where[] = ['maker', '=', $data['maker']];
        }
        if (!empty($data['number'])) {
            $where[] = ['business_number', 'like', '%' . $data['number'] . '%'];
        }
        $list = \app\api\model\SetAccountFlow::where($where)->where('customer_type', 'user')
            ->page($request->param('page', 1), $request->param('size', 10))
            ->paginate($request->param('size', 10))
            ->each(function ($v) {
                $v->maker_name = Admin::find($v['maker'])['name'];
                $v->account_type_name = AccountType::find($v['account_type_id'])['name'];
                $v->set_account_name = SetAccount::find($v['set_account_id'])['name'];
                $v->total = Service::getTotal($v);
                $v->payment = Service::getPayment($v);
                $v->balance = $v->total - $v->payment;
            });
        $info['totals'] = array_sum($list->getCollection()->column('total'));
        $info['payment'] = array_sum($list->getCollection()->column('payment'));
        $info['balance'] = array_sum($list->getCollection()->column('balance'));
        $customer = UserModel::find($data['kid']);
        $info['customer_id'] = $data['kid'];
        $info['customer_name'] = $customer->name;
        $info['customer_arrears'] = $customer->arrears;
        if (!empty($list)) {
            return json(['code' => 200, 'msg' => '成功', 'data' => array_merge($list->toArray(), $info)]);
        } else {
            return json(['code' => 500, 'msg' => '失败']);
        }
    }

    public function store(Request $request, CustomerReconciliationValidate $validate)
    {
        $data = $request->param();
        if (!$validate->scene('receipt')->check($data)) {
            return $this->returnJson(422, $validate->getError());
        }
        $data['maker'] = GetUid::getUId();
        $data['number'] = 'jxc' . time();
        $res = Service::receipt($data);
        return $res ? $this->returnJson(200, $res) : $this->returnJson(500, $res);
    }

    /**
     * 期初调整
     * @param Request $request
     * @param CustomerReconciliationValidate $validate
     * @return \think\response\Json
     */
    public function adjustment(Request $request, CustomerReconciliationValidate $validate)
    {
        $data = $request->param();
        if (!$validate->scene('adjustment')->check($data)) {
            return $this->returnJson(422, $validate->getError());
        }
        $data['maker'] = GetUid::getUId();
        $data['number'] = 'jxc' . time();
        $res = Service::adjustment($data);
        return $res ? $this->returnJson(200, $res) : $this->returnJson(500, $res);
    }

    /**
     * 快速收款
     * @param Request $request
     * @param CustomerReconciliationValidate $validate
     * @return \think\response\Json
     */
    public function quick(Request $request, CustomerReconciliationValidate $validate)
    {
        $data = $request->param();
        if (!$validate->scene('quick')->check($data)) {
            return $this->returnJson(422, $validate->getError());
        }
        $data['business_time'] = time();
        $data['maker'] = GetUid::getUId();
        $data['number'] = 'jxc' . time();
        $res = Service::quick($data);
        return $res ? $this->returnJson(200, $res) : $this->returnJson(500, $res);
    }

    /**
     * 快速收款历史
     * @param Request $request
     * @param \app\api\model\CustomerReconciliation $reconciliation
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function quickHistory(Request $request, \app\api\model\CustomerReconciliation $reconciliation)
    {
        $page = $request->param('page', 1);
        $size = $request->param('size', 10);
        $where = [];
        if (isset($request->param()['customer'])) {
            $where[] = ['customer_id', '=', $request->param()['customer']];
        }
        if (isset($request->param()['set_account'])) {
            $where[] = ['set_account_id', '=', $request->param()['set_account']];
        }
        if (isset($request->param()['account_type'])) {
            $where[] = ['account_type_id', '=', $request->param()['account_type']];
        }
        if (isset($request->param()['start_time']) && isset($request->param()['end_time'])) {
            $where[] = ['business_time', 'BETWEEN', [$request->param()['start_time'], $request->param()['end_time']]];
        }
        $res = $reconciliation->whereNotNull('payment_mode')->where($where)->page($page, $size)->paginate($size)
        ->each(function ($v) {
            $v->customer_name = UserModel::find($v['customer_id'])['name'];
            $v->account_type_name = AccountType::find($v['account_type_id'])['name'];
            $v->set_account_name = SetAccount::find($v['set_account_id'])['name'];
        });
        return $this->returnJson(200, 'ok', $res);
    }
}
